"use strict";

import { app, protocol, BrowserWindow, ipcMain, Menu } from "electron";
import { createProtocol } from "vue-cli-plugin-electron-builder/lib";
import path from "path";
// 取消安装devtools后，则不需要用到此对象，可以注释掉
// import installExtension, { VUEJS_DEVTOOLS } from "electron-devtools-installer";
const isDevelopment = process.env.NODE_ENV !== "production";

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: "app", privileges: { secure: true, standard: true } },
]);

//创建应用主窗口
const createWindow = async () => {
  const win = new BrowserWindow({
    //窗体宽度(像素)，默认800像素
    width: 800,
    //窗体高度(像素)，默认600像素
    height: 600,
    //窗口标题，如果在加载的 HTML 文件中定义了 HTML 标签 `<title>`，则该属性将被忽略。
    title: `${process.env.VUE_APP_NAME}(${process.env.VUE_APP_VERSION})`,
    //不显示窗体
    show: false,
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      // 是否开启node集成，默认false
      nodeIntegration: false,
      // 否在独立 JavaScript 环境中运行 Electron API和指定的preload 脚本. 默认为 true
      contextIsolation: true,
      //在页面运行其他脚本之前预先加载指定的脚本
      preload: path.join(__dirname, "preload.js"),
    },
    //fasle:无框窗体(没有标题栏、菜单栏)
    frame: false,
  });
  //窗体最大化
  win.maximize();
  //显示窗体
  win.show();

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
    if (!process.env.IS_TEST) win.webContents.openDevTools();
  } else {
    createProtocol("app");
    // Load the index.html when not in development
    await win.loadURL("app://./index.html");
  }

  //监听窗口重置大小后事件，若触发则给渲染进程发送消息
  win.on("resize", () => {
    win.webContents.send("window-resize", win.isMaximized());
  });

  //添加右键菜单项
  createContextMenu(win);
};

//给指定窗体创建右键菜单项
const createContextMenu = (win) => {
  //自定义右键菜单
  const template = [
    {
      label: "重新加载",
      accelerator: "ctrl+r", //快捷键
      click: function () {
        win.reload();
      },
    },
    {
      label: "调试工具",
      click: function () {
        const isDevToolsOpened = win.webContents.isDevToolsOpened();
        if (isDevToolsOpened) {
          win.webContents.closeDevTools();
        } else {
          win.webContents.openDevTools();
        }
      },
    },
  ];
  const contextMenu = Menu.buildFromTemplate(template);
  win.webContents.on("context-menu", () => {
    contextMenu.popup({ window: win });
  });
};

// Quit when all windows are closed.
app.on("window-all-closed", () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

// 只有在 app 模组的 ready 事件能触发后才能创建 BrowserWindows 实例。 您可以借助 app.whenReady() API 来等待此事件
// 通常我们使用触发器的 .on 函数来监听 Node.js 事件。
// 但是 Electron 暴露了 app.whenReady() 方法，作为其 ready 事件的专用监听器，这样可以避免直接监听 .on 事件带来的一些问题。 参见 https://github.com/electron/electron/pull/21972。
app.whenReady().then(() => {
  createWindow();

  //窗口最小化
  ipcMain.on("window-min", function (event) {
    const win = BrowserWindow.fromId(event.sender.id);
    win.minimize();
  });
  //窗口向下还原|最大化
  ipcMain.on("window-max", function (event) {
    const win = BrowserWindow.fromId(event.sender.id);
    const isMaximized = win.isMaximized();
    if (isMaximized) {
      win.unmaximize();
    } else {
      win.maximize();
    }
  });
  //窗口关闭
  ipcMain.on("window-close", function (event) {
    const win = BrowserWindow.fromId(event.sender.id);
    win.destroy();
  });
});
// 注释了此种方式改用官方推荐的专用方法来实现事件的监听
// app.on("ready", async () => {
//   //启动慢的原因在此，注释掉它后能换来极致的快感
//   //   if (isDevelopment && !process.env.IS_TEST) {
//   //     // Install Vue Devtools
//   //     try {
//   //       await installExtension(VUEJS_DEVTOOLS);
//   //     } catch (e) {
//   //       console.error("Vue Devtools failed to install:", e.toString());
//   //     }
//   //   }
//   createWindow();
// });

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === "win32") {
    process.on("message", (data) => {
      if (data === "graceful-exit") {
        app.quit();
      }
    });
  } else {
    process.on("SIGTERM", () => {
      app.quit();
    });
  }
}
